// 云函数入口文件
const cloud = require('wx-server-sdk');
// 初始化云开发
cloud.init({
  env: 'liucheng-2gmqvcgs50e86304' // 使用指定的云环境
});
const db = cloud.database();

exports.main = async (event, context) => {
  try {
    // 获取订单数据
    const result = await db.collection('Order').get();
    const orders = result.data;
    const today = new Date();

    // 过滤orderCompleted等于no的订单
    const filteredOrders = orders.filter(order => order.orderCompleted === 'no');
console.log("filteredOrders",filteredOrders)
    // 计算expectDeliTime与当前日期的天数差异，并添加到订单数据中
    filteredOrders.forEach(order => {
      const expectDeliTime = new Date(order.expectDeliTime);
      const timeDiff = expectDeliTime - today;
      const dayDiff = Math.ceil(timeDiff / (1000 * 60 * 60 * 24)); // 计算天数差异
      order.dayDiff = dayDiff;
    });

    // 按照天数差异升序排序
    filteredOrders.sort((a, b) => a.dayDiff - b.dayDiff);

    return {
      success: true,
      data: filteredOrders,
    };
  } catch (err) {
    console.error('Error fetching orders:', err);
    return {
      success: false,
      errorMessage: err.message,
    };
  }
}; 